<template>
  <div>
    <!--文件域-->
    <input type="file" name="file" id="file" style="display:none" multiple @change="upload"/>
    <button v-on:click="chooseImage">选择文件</button>
  </div>
</template>
<script>
  /**
   * 引入官方七牛 的js SDK
   */
  export default {
    data() {
      return {}
    }, methods: {
      /**
       * 选择文件
       */
      chooseImage: function () {
        // 当前浏览器是否兼容文件系统
        if (window.File && window.FileReader && window.FileList && window.Blob) {
          // 打开文件选择器
          document.getElementById('file').click();
        } else {
          alert('The File APIs are not fully supported in this browser.');
        }
      },
      /**
       * 文件上传
       * @param event
       */
      upload: function (event) {
        let file = event.target.files[0];
        if (!file) {
          return;
        }
        console.log(file);
        if (this.maxSize) {
          // TODO:文件过滤
        }
        /**
         * vue使用axios实现文件上传进度的实时更新详解.
         *
         * 相关文档地址:http://www.jb51.net/article/130995.htm;
         */
        this.$axios.get("http://192.168.100.122:8080/api/admin/getToken?fileType=").then(res => {
          let token = res.data.data;
          let formData = new FormData();
          formData.append("file", file);
          formData.append("token", token);
          var config = {
            onUploadProgress: progressEvent => {
              console.log("fuck!");
              var complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
              this.progress = complete
            }
          }
          this.$axios.post(
            'http://up-z2.qiniu.com',
            formData,
            config
          ).then(res => {
            console.log(res);
          })
        })
      },
      /**
       * @deprecated 不再使用!
       * @param event
       */
      progress: function (event) {
        // 控制进度条
        let rate = parseInt(event.loaded / event.total * 100);
        console.log(rate);
      }
    }

  }
</script>

<style scoped>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 500px;
    align: center
  }
</style>
